package com.smartparking.controller;

import com.smartparking.model.ParkingSlot;
import com.smartparking.repository.ParkingSlotRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/slot")
public class ParkingSlotController {

    private final ParkingSlotRepository repo;

    public ParkingSlotController(ParkingSlotRepository repo) {
        this.repo = repo;
    }

    @GetMapping("/list")
    public ResponseEntity<List<ParkingSlot>> list() {
        return ResponseEntity.ok(repo.findAll());
    }

    @PostMapping
    public ResponseEntity<?> create(@RequestBody Map<String, String> body) {
        String code = body.get("slotCode");
        String zone = body.getOrDefault("zone", "A");
        if (code == null) return ResponseEntity.badRequest().body(Map.of("error", "slotCode required"));
        if (repo.findBySlotCode(code).isPresent()) {
            return ResponseEntity.badRequest().body(Map.of("error", "slot exists"));
        }
        ParkingSlot s = new ParkingSlot();
        s.setSlotCode(code);
        s.setZone(zone);
        s.setStatus("FREE");
        s.setLastSeen(OffsetDateTime.now());
        repo.save(s);
        return ResponseEntity.ok(s);
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateStatus(@PathVariable Long id, @RequestBody Map<String, String> body) {
        Optional<ParkingSlot> o = repo.findById(id);
        if (o.isEmpty()) return ResponseEntity.notFound().build();
        ParkingSlot s = o.get();
        String status = body.get("status");
        if (status != null) s.setStatus(status);
        s.setLastSeen(OffsetDateTime.now());
        repo.save(s);
        return ResponseEntity.ok(s);
    }
}
